//@target illustrator

String.prototype.clearSpace = function(){
  return this.replace(/(^\s*)|(\s*$)/g, "")
}
String.prototype.toAiColor = function(){
  // 支持字符格式为: '100 70 30 0, 128 256 0' 或者 '128 0 0' (rgb 可使用 HEX)
  var colors = this.clearSpace().split(',')
  color = colors[0].hex2rgb().split(' ')
  var isRGBSpace = app.activeDocument.documentColorSpace === DocumentColorSpace.RGB
  if (colors.length === 2 && isRGBSpace) {
    color = colors[1].clearSpace().hex2rgb().split(' ')
  }
  try {
    if(color.length === 3) {
      var newColor = new RGBColor();
      newColor.red = color[0];
      newColor.green = color[1];
      newColor.blue = color[2];
    } else if(color.length === 4) {
      var newColor = new CMYKColor();
      newColor.cyan = color[0];
      newColor.magenta = color[1];
      newColor.yellow = color[2];
      newColor.black = color[3];
    }
    return newColor
  } catch (e) {
    var newColor = new RGBColor();
    newColor.red = 0;
    newColor.green = 0;
    newColor.blue = 0;
  }
  return newColor
}

String.prototype.hex2rgb = function(){
  // '#888' => '128 128 128'
  var sColor = this.toLowerCase();
  //十六进制颜色值的正则表达式
  var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
  // 如果是16进制颜色
  if (sColor && reg.test(sColor)) {
    if (sColor.length === 4) {
      var sColorNew = "#";
      for (var i=1; i<4; i+=1) {
        sColorNew += sColor.slice(i, i+1).concat(sColor.slice(i, i+1));
      }
      sColor = sColorNew;
    }
    //处理六位的颜色值
    var sColorChange = [];
    for (var i=1; i<7; i+=2) {
      sColorChange.push(parseInt("0x"+sColor.slice(i, i+2)));
    }
    return sColorChange.join(" ");
  }
  return sColor;
};


var svgCode = '<svg version="1.1" id="jettaHoriLogo" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 100 100" style="enable-background:new 0 0 100 100;" xml:space="preserve"> <path class="st0" d="M81.3,29.9L65.5,48c-1.9,2.1-4.5,3.3-7.3,3.3H41.9c-2.8,0-5.5-1.2-7.3-3.3l-2.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9h-0.2h-2.2h-1.4v2.2 h1.4v2.7l-1.4,4.6h2.6l0.3-1.1l0.8,0.4c0.9,0.5,1.8,0.7,2.8,0.7l7.8,0l0.5-2.6H92.2z M88.6,64l-0.8-3.4h-2.5l0.8,3.4H88.6z M90.1,70.8h2.8l1.6-5.5l1.7,5.5H99L96.9,64H99v-2.4h-3.3h-0.2v-2.5h-2.4v2.5H93H90V64h2.2L90.1,70.8z"/> </svg> '
var svgGroup = insertSvg(svgCode)
svgGroup.pageItems[0].pathItems[0].fillColor = '90 55 0 0, #285aff'.toAiColor()

function insertSvg(code, color) {
    var svgFileName = "inlineSVGtoAI.svg";
    var svgFile = new File("" + Folder.temp + "/" + svgFileName);
    svgFile.open("w");

    svgFile.write(code);
    svgFile.close();

    var doc = app.activeDocument;
    var placed = doc.groupItems.createFromFile(svgFile);

    $.sleep(500);
    svgFile.remove();

    return placed
}


if (app.documents.length > 0 && app.activeDocument.pathItems.length > 0) {
  var CURR_DOC = app.activeDocument;
  var CURR_ARTBOARD_INDEX = CURR_DOC.artboards.getActiveArtboardIndex()
  var CURR_ARTBOARD = CURR_DOC.artboards[CURR_ARTBOARD_INDEX].artboardRect

  setLogoGroup()
}

/* ============================================================ */
function setLogoGroup() {
  var artboardSize = _getArtboardSize(CURR_ARTBOARD)
  var artboardShortSide = artboardSize.width < artboardSize.height ? artboardSize.width : artboardSize.height
  var logoGroupScaleRatio = getLogoRatio(artboardSize)
  var LOGO_RATIO = 0.526314
  var logoGroupHeight = artboardShortSide * logoGroupScaleRatio
  var distance = logoGroupHeight * LOGO_RATIO
  _setSizeAndPosition({x: artboardSize.x + distance, y: artboardSize.y - distance}, logoGroupHeight)
}

function getLogoRatio(rectangle) {
    var ratioRange =  [1,    4/3,  7/5,  3/2,  16/9, 2,   3,   5,   9,   10];
    var logoRatios = [[0.4,  0.4,  0.4,  0.4,  0.4,  0.4, 0.4, 0.4, 0.4, 0.4],
                      [0.15, 0.15, 0.15, 0.15, 0.15, 0.2, 0.2, 0.3, 0.3, 0.4],
                      [0.15, 0.15, 0.15, 0.15, 0.15, 0.2, 0.2, 0.3, 0.3, 0.4]]
    var W = rectangle.width || 1;
    var H = rectangle.height || 1;
    var rectRatio = W > H ? W / H : H / W;
    var ratioIndex = _getArrIndex_(ratioRange, rectRatio) - 1
    var typesRange = [130, 560]
    var shortSide = W < H ? W : H;
    var typeIndex = _getArrIndex_(typesRange, shortSide)
    return logoRatios[typeIndex][ratioIndex]
}

/* ================== Public Base Function ========================================== */

// functions
// setSizeAndPosition({x: -100, y: 200}, 100)
/* todo 默认以px为单位，需要增加单位判断 */
function _setSizeAndPosition (position, height) {
  var doc = app.activeDocument;
  if (doc.selection.length < 1) {
    alert(':-) 请选好图形后，再试试')
    return
  }
  var curr = doc.selection[0]
  var ratio = curr.width / curr.height || 1

  if  (position) {
    curr.left = position.x
    curr.top = position.y
  }
  if (height) {
    curr.height = height
    curr.width = height * ratio
  }
}

function _getArtboardSize(canvas) {
    var rect = canvas.toString().split(',')
    var x1 = +rect[0]
    var y1 = +rect[1]
    var x2 = +rect[2]
    var y2 = +rect[3]
    var rectangle = {
        y: y1,
        x: x1,
        width: Math.abs(x2 - x1),
        height: Math.abs(y2 - y1)
    }
    return rectangle
}

/* ================== Js untis Functions ========================================== */

function _getArrIndex_(arr, num) {
  var index = 0;
  var len = arr.length
  if (num >= arr[len - 1]) {
    return len
  }
	while(arr[index] <= num) {
		index += 1;
	}
	return index;
}
